angular.module("personnelmanagement", ['vModal', 'PensonSelector', 'btnconqitk']).controller('usergroupCtrl', ['$scope', 'RequestPopService', 'Msg', 'sysUserInfo', 'MsgCon', function ($scope, RS, Msg, sysUserInfo, MsgCon) {
    //$scope.quanxianjson = []; //当前用户选择的权限数据

    //    var wSortLayer = "";
    //    var wSort = "";
    $scope.btnlist = { savefun: false, addinfo: false, editinfo: false, delinfo: false };
    $scope.mousePosition = function (ev) {
        if (!ev) { ev = window.event; }
        if (ev.type != "click") {
            return;
        }
        var width = 0;
        var height = 0;
        if (ev.pageX || ev.pageY) {//firefox、chrome等浏览器
            if (document.documentElement.clientWidth - ev.pageX < 450) {
                width = ev.pageX - (450 - (document.documentElement.clientWidth - ev.pageX)) - 20;
            } else {
                width = ev.pageX;
            }
            if (document.documentElement.clientHeight - ev.pageY < 480) {
                height = ev.pageY - (480 - (document.documentElement.clientHeight - ev.pageY)) - 20;
            } else {
                height = ev.pageY;
            }

            return { "left": width + "px", "top": height + "px", "position": "fixed" };
        }

        return {// IE浏览器
            "left": ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            "top": ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }


    //左侧选择器初始化
    $scope.ApiData = {
        windowModal: "2", //调用模式 1弹窗模式 2宽度大于450 3 宽度小于450
        ViceOrgOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
        ViceGroupOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
        ViceRoleOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
        ApiOpen: true, //为true时 页面打开选择器 false 关闭控制器
        menu: [//进入人员选择器的菜单

        {"id": "Group" }
        ],
        "ViceuserRoleList": [//传入的角色列表 再次点击 查询 双向绑定不能影响数据源

        ],
        "ViceuserOrgList": [//传入的部门列表 再次点击 查询 双向绑定不能影响数据源

        ],
        "ViceuserGroupList": [//传入的用户组 再次点击 查询 双向绑定不能影响数据源

        ],
        userGroupList: [],
        allTreeOrg: []

    };

    $scope.IdisNull = function () {
        if ($scope.PublicObj != undefined && $scope.PublicObj.userGroup_ID != undefined && $scope.PublicObj.userGroup_ID != "") {
            return false;
        } else {
            return true;
        }
    }

    //重置（添加子节点）
    $scope.Reset2 = function () {
        $scope.parentId = angular.copy($scope.PublicObj.userGroup_ID);
        var parentId = $scope.PublicObj.userGroup_ID;
        var wSortLayer = $scope.PublicObj.wSortLayer;
        var parentName = $scope.PublicObj.userGroup_Name;
        $scope.Reset();
        $scope.PublicObj.parentId = parentId;
        $scope.PublicObj.wSortLayer = wSortLayer;
        $scope.PublicObj.parentName = parentName;
    }

    $scope.addinfo = function () {
        if ($scope.IdisNull()) {
            $scope.Reset();
        } else {
            $scope.Reset2();
        }
    }

    //自动生成编号
    $scope.NewNo = function () {
        //        var guid = new GUID();
        //        $scope.PublicObj.userGroup_No = guid.newGUID();

        var date = new Date();
        var seperator1 = "";
        var seperator2 = "";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
                    + "" + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + date.getSeconds() + date.getMilliseconds();
        $scope.PublicObj.userGroup_No = currentdate;
    }


    //重置（添加父节点）
    $scope.Reset = function () {
        //修改父节点 选择器初始化
        $scope.ParentData = {
            ApiOpen: false,
            menu: [{ "id": "Group"}],
            userGroupList: [],
            userAuthorityList: []
        }
        //批量添加人员 选择器初始化
        $scope.PeopleData = {
            ApiOpen: false,
            style: "",
            menu: [{ "id": "User"}],
            UserList: [],
            ViceuserOrgList: [],
            ViceuserRoleList: [],
            ViceuserGroupList: [],
            searchType: [],
            DB: "0"

        }

        //批量添加负责人 选择器初始化
        $scope.personData = {

            ApiOpen: false,
            style: "",
            menu: [{ "id": "User"}],
            UserList: [],
            ViceuserOrgList: [],
            ViceuserRoleList: [],
            ViceuserGroupList: [],
            searchType: [],
            DB: "0",
            DBdata: []
        }

        //声明唯一部门对象
        $scope.PublicObj = {
            userGroup_ID: "",
            userGroup_Name: "",
            parentId: "0",
            parentName: "",
            userGroup_Num: 0,
            wSortLayer: "",
            wSort: 1,
            userGroup_No: "",
            createUserId: sysUserInfo.getuserinfo().user_ID,
            createUserName: sysUserInfo.getuserinfo().username,
            organization_ID: sysUserInfo.getuserinfo().organization_ID
        };
        $scope.NewNo();
        //声明父节点对象
        $scope.ParentObj = {};
        //声明 新增人员数组
        $scope.addPeopleList = [];
        //声明 删除人员数组
        $scope.delPeopleList = [];
        //声明 新增负责人数组
        $scope.addPersonList = [];
        //声明 删除负责人数组
        $scope.delPersonList = [];
        //声明 部门人员列表
        $scope.PeopleList = [];
        //声明 部门负责人列表
        $scope.personList = [];
        // 用户组权限id
        $scope.authority_ID = "";
    }

    $scope.addinfo();

    /**********************共有方法***********************************/

    //由于人员选择器设计多选 在此处调用需要进行数据独立
    $scope.OnlyOne = function (userGroupList) {
        if (userGroupList.length > 1) {
            userGroupList.splice(0, 1);
        }
    }
    //获取选择器所选对象
    $scope.GetSelectModal = function (userGroupList, obj) {
        try {
            if (userGroupList.length > 0) {
                return obj = userGroupList[0];
            }

        } catch (e) {
            console.log(e);
        }
    }

 //插入新增人员数组方法
    $scope.AddPeopleListFun = function (newdata, olddata,isPerson) {// 最新的人员列表 之前的人员列表 isPerson 操作的集合 0 人员列表添加 1负责人列表添加
        var index = -1;
        newdata.forEach(function (PeopleData, Findex) {
            olddata.forEach(function (PeopleList, Cindex) {
                if (PeopleData.user_ID == PeopleList.user_ID) {
                    return index = Cindex;
                }
            });
            if (index == -1) {

              if (isPerson==0) {
                 $scope.addPeopleList.push(PeopleData);
                // //将该用户加入至 需要添加的人员集合后 应将该人员从 删除的人员集合中去除
                $scope.delPeopleList.splice($scope.personListIsHas($scope.delPeopleList,PeopleData.user_ID),1);
            }else{
                   //如果不存在 则将该用户加入至 需要添加的人员集合
                   $scope.addPersonList.push(PeopleData);
                // //将该用户加入至 需要添加的人员集合后 应将该人员从 删除的人员集合中去除
                $scope.delPersonList.splice($scope.personListIsHas($scope.delPersonList,PeopleData.user_ID),1);
            }


        }
        index = -1;
    });
    }
    //插入删除人员方法
    $scope.DelPeopleListFun = function (newdata, olddata,isPerson) {// 最新的人员列表 之前的人员列表  需要删除的人员集合 需要添加的人员集合
        var index = -1;
        olddata.forEach(function (PeopleList, Cindex) {
            newdata.forEach(function (PeopleData, Findex) {
                if (PeopleData.user_ID == PeopleList.user_ID) {
                    return index = Findex;
                }
            });

            if (index == -1) {

              if (isPerson==0) {
                 $scope.delPeopleList.push(PeopleList);
                 // //将该用户加入至 需要删除的人员集合后 应将该人员从 删除的人员集合中去除
                 $scope.addPeopleList.splice($scope.personListIsHas($scope.addPeopleList,PeopleList.user_ID),1);
             }else {

               $scope.delPersonList.push(PeopleList);
                 // //将该用户加入至 需要删除的人员集合后 应将该人员从 删除的人员集合中去除
                 $scope.addPersonList.splice($scope.personListIsHas($scope.addPersonList,PeopleList.user_ID),1);
             }


         }
         index = -1;
     });
    }

    /************************获取部门对象**********************/

    //页面监听部门左侧列表选项
    var watch = $scope.$watch('ApiData.userGroupList', function (newValue, oldValue, scope) {
        try {//过滤掉非切换参数的筛选            
            if (newValue[0].userGroup_ID != oldValue[0].userGroup_ID) {
                $scope.Reset();
            }
        } catch (e) { }
        $scope.OnlyOne($scope.ApiData.userGroupList); //排除集合对象 

        if ($scope.ApiData.userGroupList.length > 0) {
            $scope.PublicObj = $scope.GetSelectModal($scope.ApiData.userGroupList, $scope.PublicObj); //取单一
            /** 如果是同一个监听的不需要请求 **/
            if (oldValue.length < 1 || newValue[0].userGroup_ID != oldValue[0].userGroup_ID)
            $scope.GetObj(); //获取数据
            //            console.log($scope.ApiData.allTreeOrg);
            if ($scope.PublicObj.userGroup_No == undefined || $scope.PublicObj.userGroup_No.length == 0) {
                $scope.NewNo();
            }
        } else {
            $scope.addinfo();

        }

    }, true);

    // 获取负责人
    var old_ID = ""; //旧的id 用于与新的id比较 如果一致 则不查找数据
    var old_personList;
    $scope.GetObj = function () {
        if (!$scope.PublicObj) {
            return;
        }
            $scope.personList=[];
        //&& old_ID == $scope.PublicObj.userGroup_ID
//        if (old_ID != "" ) {
//            //$scope.personList = old_personList;
//            return;
//        }

        $scope.parentId = angular.copy($scope.PublicObj.parentId);
        old_ID = $scope.PublicObj.userGroup_ID;
        $scope.GetNumCount($scope.PublicObj.userGroup_ID);
        $scope.isloading = true;
        RS.GetGroup({ userGroup_ID: $scope.PublicObj.userGroup_ID, userId: sysUserInfo.getuserinfo().user_ID, user_Organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (Data) {
            $scope.isloading = false;
            $scope.personData.UserList = [];
            if (Data.errorcode == "0") {
                $scope.personList = angular.copy(Data.datas);
                old_personList = angular.copy(Data.datas);
            } else if (Data.errorcode != "0") {
            }
        }, function callback() {
            Msg.error("请求数据有误");

        });
        $scope.isloading = true;
        RS.GetAuthority({ bqx_xid: $scope.PublicObj.userGroup_ID }).then(function (Data) {
            $scope.isloading = false;
            if (Data.errorcode == "0") {
                if (Data.data != null) {
                    if (Data.data.bqx_quanxian != null && Data.data.bqx_quanxian != "") {
                        var quanxianstr = Data.data.bqx_quanxian.split(",");
                        $scope.ParentData.userAuthorityList = quanxianstr;
                    } else {
                        $scope.ParentData.userAuthorityList = [];
                    }
                    $scope.authority_ID = Data.data.bqx_Id;
                } else {
                    $scope.ParentData.userAuthorityList = [];
                }
            } else if (Data.errorcode != "0") {
            }
        }, function callback() {
            Msg.error("请求数据有误");

        });
    }
    //获取部门人员列表
    $scope.GetNumCount = function (id) {
        RS.GetPersonnelCount({ id: id, optype: 3, orgId: sysUserInfo.getuserinfo().organization_ID, powerLV: sysUserInfo.getuserinfo().powerLV }).then(function (Data) {
            if (Data.errorcode == "0") {
                $scope.isGetCountNum = true;
                if ($scope.PeopleList.length > 0) {
                    $scope.PublicObj.userGroup_Num = $scope.PeopleList.length;
                } else {
                    $scope.PublicObj.userGroup_Num = Data.numCount;
                }
            }
        });
    }

    //*********************修改父节点***************************/

    var guid = new GUID();
    //页面监听父集列表选项
    $scope.WatchParentList = function () {
        var watch = $scope.$watch('ParentData.userGroupList', function (newValue, oldValue, scope) {
            $scope.OnlyOne($scope.ParentData.userGroupList); //排除集合对象 
            if ($scope.ParentData.userGroupList.length > 0) {
                $scope.ParentObj = $scope.GetSelectModal($scope.ParentData.userGroupList, $scope.ParentObj); //取单一

                if ($scope.PublicObj.userGroup_ID == $scope.ParentObj.userGroup_ID) {
                    Msg.warning("父节点不能选择自己！");
                } else {
                    $scope.PublicObj.parentName = $scope.ParentObj.userGroup_Name;
                    $scope.PublicObj.parentId = $scope.ParentObj.userGroup_ID;
                    $scope.PublicObj.wSortLayer = $scope.ParentObj.wSortLayer + "-" + guid.newGUID();
                }
            }
        }, true);
    }

    //监控选择左侧树节点后对象的变化
    /*
    $scope.$watch('PublicObj', function (newValue, oldValue, scope) {
    if (wSortLayer == "") { wSortLayer = $scope.PublicObj.wSortLayer; }
    if (wSort == "") { wSort = $scope.PublicObj.wSort; }
    }, true);
    */
    //点击修改事件
    $scope.UpdateParentFun = function (event) {
        $scope.ParentData.ApiOpen = true;
        $scope.ParentData.event = event;
        $scope.WatchParentList(); //启动监听
    }

    //***********************批量添加人员*****************//
    $scope.PeopleListHasData = function () {
        $scope.PeopleData.UserList = angular.copy($scope.PeopleList);
        $scope.PublicObj.userGroup_Num = $scope.PeopleData.UserList.length;
        $scope.PeopleData.ApiOpen = true;
        $scope.WatchUserList();
    }
    //新增人员点击事件
    $scope.AddUserListFun = function (event) {
        $scope.PeopleData.style = $scope.mousePosition(event);
        if ($scope.PublicObj.userGroup_Num <= 0) {
            $scope.PeopleData.DB = "0";
            $scope.PeopleListHasData();
        } else {
            $scope.PeopleData.DB = 1;
            //判断该部门中的用户集合是否为空 如果为空 先加载该部门用户数据
            if ($scope.PeopleList.length <= 0 && $scope.PublicObj && $scope.PublicObj.userGroup_ID != "") {
                $scope.PeopleData.searchType.push(7);
                $scope.isloading = true;
                RS.personnelUser({ searchType: $scope.PeopleData.searchType, groupList: $scope.PublicObj, userId: sysUserInfo.getuserinfo().user_ID, organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (user) {
                    $scope.isloading = false;
                    if (user.errorcode == "0") {
                        $scope.PeopleList = angular.copy(user.datas);
                        $scope.PeopleListHasData();
                    }
                }, function callback() {
                    Msg.error("请求数据有误");

                });
            } else {
                $scope.PeopleListHasData();
            }
        }
    }

    //监听人员列表事件
    $scope.WatchUserList = function () {
        //由于人员数量可能过大 因此此处不实时监听人员列表变化 而是监听关闭
        var watch = $scope.$watch('PeopleData.ApiOpen', function (newValue, oldValue, scope) {
            //判断 新数据源比旧数据源长度大的情况下 新增了用户
            if (!newValue) { //关闭事件
                // statement
                $scope.AddPeopleListFun($scope.PeopleData.UserList, $scope.PeopleList, 0);
                $scope.DelPeopleListFun($scope.PeopleData.UserList, $scope.PeopleList,0);
                //做完比较后。应将旧数据更新
                $scope.PeopleList = angular.copy($scope.PeopleData.UserList);
                $scope.PublicObj.userGroup_Num = $scope.PeopleList.length;
            }
        }, true);
    }

    //添加负责人
    $scope.AddpersonFun = function (event) {
        $scope.personData.style = $scope.mousePosition(event);

        //将下一步方法封装 因为上面要异步调用 
        $scope.nextGetShow = function () {
            // if ($scope.PeopleList.length > 0 || $scope.personList.length > 0) {  //判断是否已添加角色人员 如果已添加 角色列表则显示已添加的角色人员
            //     $scope.personData.DBdata = angular.copy($scope.PeopleList);
            //     $scope.personData.DB = "1";
            // } else {
            $scope.personData.DB = "0";
            // }
            //判断 人员选择器中是否有已选人员 如果没有 将已选人员加入人员选择器中
            $scope.personList.forEach(function (element, index) {
                //将负责人集合 进行双向绑定
                var has = false;
                //去重业务
                $scope.personData.UserList.forEach(function (child, childindex) {
                    //判断是否已存在 
                    if (child.user_ID == element.user_ID) {
                        has = true;
                        return;
                    }
                });
                //如果不存在 则添加
                if (!has) {
                    $scope.personData.UserList.push(element);
                }
            });
            //判断 人员选择器中是否含有 已经不存在的 已选人员 如果有 将不存在的人员已选人员 删除
            $scope.personDataNoHasList = [];
            $scope.personData.UserList.forEach(function (element, index) {
                //将负责人集合 进行双向绑定
                var has = false;
                //去重业务
                $scope.personList.forEach(function (child, childindex) {
                    //判断是否已存在 
                    if (child.user_ID == element.user_ID) {
                        has = true;
                        return;
                    }
                });
                //如果不存在 则添加
                if (!has) {
                    $scope.personDataNoHasList.push(index);
                }
            });
            $scope.personDataNoHasList.forEach(function (element, index) {
                $scope.personData.UserList.splice(element, 1);
            });

            console.log($scope.personList.length);
            $scope.personData.ApiOpen = true;
            $scope.WatchpersonDataList();
        }

        //判断是否已加载用户列表。如果未加载 先进行加载
        if ($scope.PeopleList.length <= 0 && $scope.PublicObj && $scope.PublicObj.userGroup_ID != "") {
            $scope.PeopleData.searchType.push(7);
            $scope.isloading = true;
            RS.personnelUser({ searchType: $scope.PeopleData.searchType, groupList: $scope.PublicObj, userId: sysUserInfo.getuserinfo().user_ID, organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (user) {
                $scope.isloading = false;
                if (user.errorcode == "0") {
                    $scope.PeopleList = angular.copy(user.datas);
                    $scope.nextGetShow();
                } else {
                    $scope.nextGetShow();
                }
            }, function callback() {
                Msg.error("请求数据有误");

            });
        } else {
            $scope.nextGetShow();
        }



    }
        //删除某个负责人
    $scope.DelPersonListFun = function (id) {
        $scope.delPersonList.push({ "user_ID": id });
        $scope.personList.splice($scope.personListIsHas($scope.personList, id), 1);
    }
    $scope.personListIsHas = function (data, id) {
        var listindex = -1;
        data.forEach(function (element, index) {

            if (element.user_ID == id) {
                listindex = index;
                return;
            }

        });
        return listindex;
    }
    //监听负责人列表事件
    $scope.WatchpersonDataList = function () {
        var watch = $scope.$watch('personData.UserList', function (newValue, oldValue, scope) {
            //判断 新数据源比旧数据源长度大的情况下 新增了用户
            // statement
            // if (!newValue) {
  $scope.AddPeopleListFun($scope.personData.UserList, $scope.personList, 1);
    $scope.DelPeopleListFun($scope.personData.UserList, $scope.personList, 1);
                //做完比较后。应将旧数据更新
                $scope.personList = angular.copy($scope.personData.UserList);
                $scope.personData.DBdata = [];
            // }

        }, true);
    }

    //验证排序码是否可用
    $scope.CheckSort = function () {
        if ($scope.PublicObj.wSort) {
            $scope.isloading = true;
            RS.GetSort({ wSort: $scope.PublicObj.wSort, type: 3, parentId: $scope.PublicObj.parentId }).then(function (data) {
                $scope.isloading = false;
                if (data.errorcode == "0") {
                    //                    console.log("排序码可用");
                } else if (data.errorcode == "26") {
                    Msg.info("显示顺序不能与同级组织机构的显示顺序重复");
                } else if (data.errorcode == "6") {
                    Msg.error("系统内部错误");
                } else if (data.errorcode == "5") {
                    Msg.error("连接不上数据库");
                } else if (data.errorcode == "1") {
                    Msg.error("失败");
                }
            }, function callback() {
                Msg.error("请求数据有误");

            });
        } else {
            Msg.error("请填写显示顺序");
        }
    }

    //用户组删除
    $scope.delinfo = function () {
        if (!$scope.PublicObj.userGroup_ID || $scope.PublicObj.userGroup_ID == "") {
            Msg.error("请选择要删除的用户组");
            return;
        }
        MsgCon.delnoicon().then(function (flag) {   // 删除弹框
            if (flag) {
                $scope.isloading = true;
                RS.DelGroup({ userGroup_ID: $scope.PublicObj.userGroup_ID, management_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (data) {
                    $scope.isloading = false;
                    if (data.errorcode == "0") {
                        $scope.ArrayRecursion($scope.ApiData.allTreeOrg, $scope.PublicObj, $scope.PublicObj.parentId, 2);
                        Msg.success("删除成功");
                        $scope.Reset();
                    }
                }, function callback() {
                    Msg.error("请求数据有误");

                });
            }
        });
    }

    //保存操作
    $scope.SaveFun = function () {

        if ($scope.PublicObj.userGroup_No == undefined || $scope.PublicObj.userGroup_No.length == 0) { Msg.warning('节点编号不能为空！'); return; }
        if ($scope.PublicObj.userGroup_Name == undefined || $scope.PublicObj.userGroup_Name.length == 0) { Msg.warning('节点名称不能为空！'); return; }
        if ($scope.PublicObj.wSort == undefined || $scope.PublicObj.wSort == 0) { Msg.warning('显示顺序不能为空！'); return; }

   
        var APersonList = [];
        // 初始化添加负责人
        if ($scope.addPersonList.length > 0) {
            angular.forEach($scope.addPersonList, function (obj, index, arr) {
                APersonList.push({ 'userId': obj.user_ID });
            });
        }
        var DPersonList = [];
        if ($scope.delPersonList.length > 0) {
            angular.forEach($scope.delPersonList, function (obj, index, arr) {
                DPersonList.push({ 'userId': obj.user_ID });
            });
        }

        //排序码
        var guid = new GUID();
        if ($scope.PublicObj.userGroup_ID == "" && $scope.PublicObj.parentId == "0") {
            $scope.PublicObj.wSortLayer = guid.newGUID();
        } else if ($scope.PublicObj.userGroup_ID == "" && $scope.PublicObj.parentId != "0") {
            $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer + "-" + guid.newGUID();
        } else if ($scope.PublicObj.userGroup_ID != "" && $scope.PublicObj.parentId == "0") {
           // $scope.PublicObj.wSortLayer = guid.newGUID();
        } else {
     
        }
        // 负责人将自己添加
        if (sysUserInfo.getuserinfo().powerLV == "3" && !$scope.PublicObj.userGroup_ID) {
            $scope.addPeopleList.push({ 'user_ID': sysUserInfo.getuserinfo().user_ID });
            APersonList.push({ 'userId': sysUserInfo.getuserinfo().user_ID });
        }
        //保存数据
        $scope.isloading = true;
        RS.AddEditGroup({ data: $scope.PublicObj, addPeopleList: $scope.addPeopleList, delPeopleList: $scope.delPeopleList, addPersonList: APersonList, delPersonList: DPersonList, authority_ID: $scope.authority_ID, authority: $scope.ParentData.userAuthorityList.join(","), organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (data) {
            $scope.isloading = false;
            $scope.addPersonList = [];
            $scope.delPersonList = [];
            if (data.errorcode == "0") {
                if (!$scope.PublicObj.userGroup_ID) {
                    Msg.success("新增成功");
                    $scope.PublicObj.userGroup_ID = data.id;
                    $scope.PublicObj.haschildren = 0;
                    // 如果是负责人的那么添加后再给本地添加信息
                    if (sysUserInfo.getuserinfo().powerLV == "3") {
                        if (!sysUserInfo.getuserinfo().hasOwnProperty("userGroupList"))
                            sysUserInfo.getuserinfo().userGroupList = [];
                        $scope.olduserinfo = sysUserInfo.getuserinfo();
                        $scope.PublicObj.boss = true;
                        $scope.olduserinfo.userGroupList.push($scope.PublicObj);                        
                        // 添加设置负责人的部门
                        sysUserInfo.setuserinfo($scope.olduserinfo);
                    }
                } else {
                    Msg.success("修改成功");
                    $scope.ArrayRecursion($scope.ApiData.allTreeOrg, $scope.PublicObj, $scope.parentId, 2);
                }

                $scope.ArrayRecursion($scope.ApiData.allTreeOrg, $scope.PublicObj, "", 1);
                // //初始化用户组对象
                // $scope.PublicObj = {
                //     userGroup_ID: "",
                //     userGroup_Name: "",
                //     parentId: "0",
                //     parentName: "",
                //     userGroup_Num: 0,
                //     wSortLayer: "",
                //     wSort: 1,
                //     userGroup_No: "",
                //     createUserId: sysUserInfo.getuserinfo().user_ID,
                //     createUserName: sysUserInfo.getuserinfo().username,
                //     organization_ID: sysUserInfo.getuserinfo().organization_ID
                // };
                 $scope.ApiData.userGroupList = [];
                // $scope.NewNo();
                //实现新增修改无需刷新
                //判定是否修改了父集

            } else {
                Msg.error("操作失败");
            }
        }, function callback() {
            Msg.error("请求数据有误");

        });
        $scope.PublicObj.userGroup_Name = decodeURI($scope.PublicObj.userGroup_Name);

    }
    $scope.SetChildNode = function (id, newnum) {
        RS.SetChildNode({ id: id, optype: 3, newnum: newnum }).then(function (Data) {
            if (Data.errorcode != "0") {
                Msg.error("节点子集添加失败");
            }
        }, function callback() {
            Msg.error("节点子集请求数据有误");
        });
    }
    //递归修改 DataArray:数据集合 childObj:对象 parentId: 父集id fun :执行方法 1 新增 2删除
    $scope.ArrayRecursion = function (DataArray, childObj, parentId, fun) {
        if (fun == 1) {
            if (childObj.parentId == "0") {
                try {
                    DataArray.push(childObj);
                } catch (e) {
                    DataArray = [];
                    DataArray.push(childObj);
                }

            } else {
                DataArray.forEach(function (element, index) {
                    if (element.userGroup_ID == childObj.parentId) {
                        element.haschildren++;
                        $scope.SetChildNode(element.userGroup_ID, element.haschildren);
                        if (element.children) {
                            element.children.push(childObj);
                        } else {
                            element.children = [];
                            element.children.push(childObj);
                        }
                    } else {
                        if (element.children) {
                            $scope.ArrayRecursion(element.children, childObj, "", 1);
                        }
                    }
                });
            }
        } else if (fun == 2) {
            DataArray.forEach(function (element, index) {
                if (element.userGroup_ID == parentId) {
                    element.haschildren--;
                    $scope.SetChildNode(element.userGroup_ID, element.haschildren);
                    try {
                        element.children.splice($scope.containsGroup(element.children, $scope.PublicObj), 1);
                    } catch (e) {
                        console.log(e);
                    }
                } else if (parentId == "0" && childObj.userGroup_ID == element.userGroup_ID) {
                    DataArray.splice($scope.containsGroup(DataArray, element), 1);
                } else {
                    if (element.children) {
                        $scope.ArrayRecursion(element.children, childObj, parentId, 2);
                    } else {
                        if (element.userGroup_ID == $scope.PublicObj.userGroup_ID) {
                            DataArray.splice($scope.containsGroup(DataArray, $scope.PublicObj), 1);
                        }
                    }
                }
            });
        }
    }

    ApiOpenOk = function () {
        $scope.ApiData.ApiOpen = true;
    }

    $scope.containsGroup = function (arr, obj) {
        try {
            var i = arr.length;
            while (i--) {

                if (arr[i].userGroup_ID === obj.userGroup_ID) {
                    return i;
                }
            }
            return -1;
        } catch (e) {
            // statements
            return -1;
        }
    }
} ]);